<template>
  <div class="leave-apply-container">
    <h2>{{ getUserTitle() }}</h2>
    
    <el-tabs v-model="activeTab">
      <el-tab-pane :label="getTabLabel('apply')" name="apply">
        <div v-if="userRole === 'student'">
          <el-card>
            <template #header>
              <div class="card-header">
                <span>请假申请表</span>
              </div>
            </template>
            
            <el-form :model="leaveForm" :rules="rules" ref="leaveForm" label-width="120px">
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="请假类型" prop="leaveType">
                    <el-select v-model="leaveForm.leaveType" placeholder="请选择请假类型" style="width: 100%">
                      <el-option label="病假" value="病假"></el-option>
                      <el-option label="事假" value="事假"></el-option>
                      <el-option label="公假" value="公假"></el-option>
                      <el-option label="其他" value="其他"></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                
                <el-col :span="12">
                  <el-form-item label="紧急程度">
                    <el-select v-model="leaveForm.urgency" placeholder="请选择紧急程度" style="width: 100%">
                      <el-option label="一般" value="一般"></el-option>
                      <el-option label="紧急" value="紧急"></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                
                <el-col :span="12">
                  <el-form-item label="开始时间" prop="startTime">
                    <el-date-picker
                      v-model="leaveForm.startTime"
                      type="datetime"
                      placeholder="请选择开始时间"
                      style="width: 100%"
                      :disabled-date="disabledStartDate">
                    </el-date-picker>
                  </el-form-item>
                </el-col>
                
                <el-col :span="12">
                  <el-form-item label="结束时间" prop="endTime">
                    <el-date-picker
                      v-model="leaveForm.endTime"
                      type="datetime"
                      placeholder="请选择结束时间"
                      style="width: 100%"
                      :disabled-date="disabledEndDate">
                    </el-date-picker>
                  </el-form-item>
                </el-col>
                
                <el-col :span="12">
                  <el-form-item label="请假天数">
                    <el-input v-model="leaveDays" disabled>
                      <template #append>天</template>
                    </el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              
              <el-form-item label="请假理由" prop="reason">
                <el-input 
                  v-model="leaveForm.reason" 
                  type="textarea" 
                  :rows="4" 
                  placeholder="请详细说明请假理由">
                </el-input>
              </el-form-item>
              
              <el-form-item label="证明材料">
                <el-upload
                  v-model:file-list="fileList"
                  class="upload-demo"
                  action="/api/upload"
                  :on-preview="handlePreview"
                  :on-remove="handleRemove"
                  :before-remove="beforeRemove"
                  :limit="3"
                  :on-exceed="handleExceed"
                  multiple>
                  <el-button size="small" type="primary">点击上传</el-button>
                  <template #tip>
                    <div class="el-upload__tip">
                      支持jpg/png/pdf/doc等格式，单个文件不超过10MB，最多上传3个文件
                    </div>
                  </template>
                </el-upload>
              </el-form-item>
              
              <el-form-item>
                <el-button type="primary" @click="submitLeave">提交申请</el-button>
                <el-button @click="resetForm">重置</el-button>
              </el-form-item>
            </el-form>
          </el-card>
        </div>
        
        <div v-else-if="userRole === 'teacher'">
          <el-card>
            <template #header>
              <div class="card-header">
                <span>待审批请假申请</span>
                <el-button @click="refreshRecords">刷新</el-button>
              </div>
            </template>
            
            <el-table :data="pendingLeaves" style="width: 100%" v-loading="loading">
              <el-table-column prop="id" label="申请编号" width="120"></el-table-column>
              <el-table-column prop="studentName" label="申请人" width="120"></el-table-column>
              <el-table-column prop="leaveType" label="请假类型" width="100"></el-table-column>
              <el-table-column prop="startTime" label="开始时间" width="180"></el-table-column>
              <el-table-column prop="endTime" label="结束时间" width="180"></el-table-column>
              <el-table-column prop="days" label="天数" width="80"></el-table-column>
              <el-table-column prop="urgency" label="紧急程度" width="100">
                <template #default="scope">
                  <el-tag :type="scope.row.urgency === '紧急' ? 'danger' : 'info'">
                    {{ scope.row.urgency }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="200">
                <template #default="scope">
                  <el-button size="small" @click="viewDetail(scope.row)">详情</el-button>
                  <el-button size="small" type="primary" @click="approveLeave(scope.row, 'approved')">批准</el-button>
                  <el-button size="small" type="danger" @click="approveLeave(scope.row, 'rejected')">拒绝</el-button>
                </template>
              </el-table-column>
            </el-table>
            
            <el-pagination
              layout="prev, pager, next"
              :total="total"
              :page-size="pageSize"
              @current-change="handlePageChange"
              class="pagination">
            </el-pagination>
          </el-card>
        </div>
        
        <div v-else-if="userRole === 'principal'">
          <el-card>
            <template #header>
              <div class="card-header">
                <span>待审批教师请假申请</span>
                <el-button @click="refreshRecords">刷新</el-button>
              </div>
            </template>
            
            <el-table :data="pendingTeacherLeaves" style="width: 100%" v-loading="loading">
              <el-table-column prop="id" label="申请编号" width="120"></el-table-column>
              <el-table-column prop="teacherName" label="申请人" width="120"></el-table-column>
              <el-table-column prop="leaveType" label="请假类型" width="100"></el-table-column>
              <el-table-column prop="startTime" label="开始时间" width="180"></el-table-column>
              <el-table-column prop="endTime" label="结束时间" width="180"></el-table-column>
              <el-table-column prop="days" label="天数" width="80"></el-table-column>
              <el-table-column prop="urgency" label="紧急程度" width="100">
                <template #default="scope">
                  <el-tag :type="scope.row.urgency === '紧急' ? 'danger' : 'info'">
                    {{ scope.row.urgency }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="200">
                <template #default="scope">
                  <el-button size="small" @click="viewDetail(scope.row)">详情</el-button>
                  <el-button size="small" type="primary" @click="approveLeave(scope.row, 'approved')">批准</el-button>
                  <el-button size="small" type="danger" @click="approveLeave(scope.row, 'rejected')">拒绝</el-button>
                </template>
              </el-table-column>
            </el-table>
            
            <el-pagination
              layout="prev, pager, next"
              :total="total"
              :page-size="pageSize"
              @current-change="handlePageChange"
              class="pagination">
            </el-pagination>
          </el-card>
        </div>
      </el-tab-pane>
      
      <el-tab-pane :label="getTabLabel('records')" name="records">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>{{ getRecordTitle() }}</span>
              <el-button @click="refreshRecords">刷新</el-button>
            </div>
          </template>
          
          <el-table :data="leaveRecords" style="width: 100%" v-loading="loading">
            <el-table-column prop="id" label="申请编号" width="120"></el-table-column>
            <el-table-column v-if="userRole !== 'student'" prop="studentName" label="申请人" width="120"></el-table-column>
            <el-table-column v-if="userRole === 'principal'" prop="teacherName" label="申请人" width="120"></el-table-column>
            <el-table-column prop="leaveType" label="请假类型" width="100"></el-table-column>
            <el-table-column prop="startTime" label="开始时间" width="180"></el-table-column>
            <el-table-column prop="endTime" label="结束时间" width="180"></el-table-column>
            <el-table-column prop="days" label="天数" width="80"></el-table-column>
            <el-table-column prop="status" label="状态" width="120">
              <template #default="scope">
                <el-tag :type="getStatusType(scope.row.status)">
                  {{ scope.row.status }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column v-if="userRole !== 'principal'" prop="approver" label="审批人" width="120"></el-table-column>
            <el-table-column label="操作" width="150">
              <template #default="scope">
                <el-button size="small" @click="viewDetail(scope.row)">详情</el-button>
                <el-button 
                  v-if="userRole === 'student' && scope.row.status === '待审批'" 
                  size="small" 
                  type="danger" 
                  @click="cancelLeave(scope.row)">
                  撤销
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          
          <el-pagination
            layout="prev, pager, next"
            :total="total"
            :page-size="pageSize"
            @current-change="handlePageChange"
            class="pagination">
          </el-pagination>
        </el-card>
      </el-tab-pane>
    </el-tabs>
    
    <!-- 请假详情对话框 -->
    <el-dialog v-model="detailDialogVisible" :title="getDetailTitle()" width="50%">
      <el-form :model="selectedLeave" label-width="100px">
        <el-form-item label="申请编号:">
          <span>{{ selectedLeave.id }}</span>
        </el-form-item>
        <el-form-item v-if="userRole !== 'student'" label="申请人:">
          <span>{{ selectedLeave.studentName || selectedLeave.teacherName }}</span>
        </el-form-item>
        <el-form-item label="请假类型:">
          <span>{{ selectedLeave.leaveType }}</span>
        </el-form-item>
        <el-form-item label="开始时间:">
          <span>{{ selectedLeave.startTime }}</span>
        </el-form-item>
        <el-form-item label="结束时间:">
          <span>{{ selectedLeave.endTime }}</span>
        </el-form-item>
        <el-form-item label="请假天数:">
          <span>{{ selectedLeave.days }} 天</span>
        </el-form-item>
        <el-form-item label="请假理由:">
          <span>{{ selectedLeave.reason }}</span>
        </el-form-item>
        <el-form-item label="状态:">
          <el-tag :type="getStatusType(selectedLeave.status)">
            {{ selectedLeave.status }}
          </el-tag>
        </el-form-item>
        <el-form-item v-if="userRole !== 'principal'" label="审批人:">
          <span>{{ selectedLeave.approver || '暂无' }}</span>
        </el-form-item>
        <el-form-item v-if="userRole !== 'principal'" label="审批意见:">
          <span>{{ selectedLeave.approvalComment || '暂无' }}</span>
        </el-form-item>
        <el-form-item v-if="userRole !== 'student'" label="紧急程度:">
          <el-tag :type="selectedLeave.urgency === '紧急' ? 'danger' : 'info'">
            {{ selectedLeave.urgency }}
          </el-tag>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="detailDialogVisible = false">关闭</el-button>
          <el-button v-if="userRole !== 'student'" type="primary" @click="openApproveDialog">审批</el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- 审批对话框 -->
    <el-dialog v-model="approveDialogVisible" :title="getApprovalTitle()" width="50%" v-if="userRole !== 'student'">
      <el-form :model="approveForm" label-width="100px">
        <el-form-item label="申请编号:">
          <span>{{ approveForm.id }}</span>
        </el-form-item>
        <el-form-item label="申请人:">
          <span>{{ approveForm.studentName || approveForm.teacherName }}</span>
        </el-form-item>
        <el-form-item label="审批意见:">
          <el-input
            v-model="approveForm.comment"
            type="textarea"
            :rows="4"
            placeholder="请输入审批意见">
          </el-input>
        </el-form-item>
        <el-form-item label="审批结果:">
          <el-radio-group v-model="approveForm.result">
            <el-radio label="approved">批准</el-radio>
            <el-radio label="rejected">拒绝</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="approveDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitApproval">提交审批</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'LeaveApply',
  data() {
    return {
      userRole: 'student', // 默认为学生
      activeTab: 'apply',
      leaveForm: {
        leaveType: '',
        urgency: '一般',
        startTime: '',
        endTime: '',
        reason: ''
      },
      rules: {
        leaveType: [
          { required: true, message: '请选择请假类型', trigger: 'change' }
        ],
        startTime: [
          { required: true, message: '请选择开始时间', trigger: 'change' }
        ],
        endTime: [
          { required: true, message: '请选择结束时间', trigger: 'change' }
        ],
        reason: [
          { required: true, message: '请输入请假理由', trigger: 'blur' }
        ]
      },
      fileList: [],
      loading: false,
      pendingLeaves: [
        {
          id: 'QJ20241021015',
          studentName: '张三',
          leaveType: '病假',
          startTime: '2024-10-22 09:00:00',
          endTime: '2024-10-23 18:00:00',
          days: 2,
          urgency: '一般',
          status: '待审批',
          reason: '感冒发烧，需要就医治疗'
        },
        {
          id: 'QJ20241021012',
          studentName: '李四',
          leaveType: '事假',
          startTime: '2024-10-25 08:00:00',
          endTime: '2024-10-25 18:00:00',
          days: 1,
          urgency: '紧急',
          status: '待审批',
          reason: '家中有急事需要处理'
        }
      ],
      pendingTeacherLeaves: [
        {
          id: 'QJ20241021025',
          teacherName: '王老师',
          leaveType: '事假',
          startTime: '2024-10-28 09:00:00',
          endTime: '2024-10-29 18:00:00',
          days: 2,
          urgency: '一般',
          status: '待审批',
          reason: '家中有事需要处理'
        },
        {
          id: 'QJ20241021022',
          teacherName: '李老师',
          leaveType: '病假',
          startTime: '2024-10-30 09:00:00',
          endTime: '2024-11-01 18:00:00',
          days: 3,
          urgency: '紧急',
          status: '待审批',
          reason: '身体不适，需要治疗'
        }
      ],
      leaveRecords: [
        {
          id: 'QJ20241021001',
          studentName: '张三',
          teacherName: '王老师',
          leaveType: '病假',
          startTime: '2024-10-22 09:00:00',
          endTime: '2024-10-23 18:00:00',
          days: 2,
          status: '待审批',
          approver: '',
          approvalComment: '',
          reason: '感冒发烧，需要就医治疗'
        },
        {
          id: 'QJ20241015008',
          studentName: '李四',
          teacherName: '李老师',
          leaveType: '事假',
          startTime: '2024-10-16 08:00:00',
          endTime: '2024-10-16 18:00:00',
          days: 1,
          status: '已批准',
          approver: '王老师',
          approvalComment: '批准',
          reason: '家中有事，需要处理'
        }
      ],
      total: 100,
      pageSize: 10,
      currentPage: 1,
      detailDialogVisible: false,
      approveDialogVisible: false,
      selectedLeave: {},
      approveForm: {
        id: '',
        studentName: '',
        teacherName: '',
        comment: '',
        result: 'approved'
      }
    }
  },
  computed: {
    leaveDays() {
      if (this.leaveForm.startTime && this.leaveForm.endTime) {
        const start = new Date(this.leaveForm.startTime)
        const end = new Date(this.leaveForm.endTime)
        const diffTime = Math.abs(end - start)
        const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24))
        return diffDays
      }
      return 0
    }
  },
  mounted() {
    // 获取用户角色
    const userStr = localStorage.getItem('user')
    if (userStr) {
      try {
        const user = JSON.parse(userStr)
        this.userRole = user.role
      } catch (e) {
        console.error('解析用户信息失败:', e)
      }
    }
  },
  methods: {
    getUserTitle() {
      switch (this.userRole) {
        case 'student':
          return '请假申请'
        case 'teacher':
          return '请假审批'
        case 'principal':
          return '教师请假审批'
        default:
          return '请假申请'
      }
    },
    getTabLabel(tab) {
      if (tab === 'apply') {
        switch (this.userRole) {
          case 'student':
            return '申请请假'
          case 'teacher':
            return '待审批'
          case 'principal':
            return '教师请假审批'
          default:
            return '申请请假'
        }
      } else {
        switch (this.userRole) {
          case 'student':
            return '申请记录'
          case 'teacher':
            return '审批记录'
          case 'principal':
            return '审批记录'
          default:
            return '申请记录'
        }
      }
    },
    getRecordTitle() {
      switch (this.userRole) {
        case 'student':
          return '我的请假记录'
        case 'teacher':
          return '我的审批记录'
        case 'principal':
          return '教师请假审批记录'
        default:
          return '请假记录'
      }
    },
    getDetailTitle() {
      switch (this.userRole) {
        case 'student':
          return '请假详情'
        case 'teacher':
          return '审批详情'
        case 'principal':
          return '教师请假详情'
        default:
          return '详情'
      }
    },
    getApprovalTitle() {
      switch (this.userRole) {
        case 'teacher':
          return '学生请假审批'
        case 'principal':
          return '教师请假审批'
        default:
          return '审批'
      }
    },
    disabledStartDate(time) {
      return time.getTime() < Date.now() - 8.64e7
    },
    disabledEndDate(time) {
      if (!this.leaveForm.startTime) {
        return false
      }
      return time.getTime() < new Date(this.leaveForm.startTime).getTime()
    },
    submitLeave() {
      if (this.userRole !== 'student') return
      this.$refs.leaveForm.validate((valid) => {
        if (valid) {
          this.$message.success('请假申请提交成功，请等待审批！')
          this.resetForm()
        } else {
          this.$message.error('请完善请假信息')
          return false
        }
      })
    },
    resetForm() {
      this.$refs.leaveForm.resetFields()
      this.fileList = []
    },
    handleRemove(file, fileList) {
      console.log(file, fileList)
    },
    handlePreview(file) {
      console.log(file)
    },
    handleExceed(files, fileList) {
      this.$message.warning('最多只能上传3个文件')
    },
    beforeRemove(uploadFile, uploadFiles) {
      return this.$confirm(`确定移除 ${uploadFile.name}？`)
    },
    refreshRecords() {
      this.loading = true
      // 模拟刷新数据
      setTimeout(() => {
        this.loading = false
        this.$message.success('刷新成功')
      }, 500)
    },
    handlePageChange(page) {
      this.currentPage = page
      this.loading = true
      // 模拟分页加载
      setTimeout(() => {
        this.loading = false
      }, 500)
    },
    getStatusType(status) {
      const statusMap = {
        '待审批': 'warning',
        '已批准': 'success',
        '已拒绝': 'danger',
        '已撤销': 'info'
      }
      return statusMap[status] || 'info'
    },
    viewDetail(leave) {
      this.selectedLeave = leave
      this.detailDialogVisible = true
    },
    cancelLeave(leave) {
      if (this.userRole !== 'student') return
      this.$confirm('确定要撤销此请假申请吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        leave.status = '已撤销'
        this.$message.success('请假申请已撤销')
      }).catch(() => {
        // 取消操作
      })
    },
    approveLeave(leave, result) {
      if (this.userRole === 'student') return
      this.approveForm.id = leave.id
      this.approveForm.studentName = leave.studentName
      this.approveForm.teacherName = leave.teacherName
      this.approveForm.result = result
      this.approveDialogVisible = true
    },
    openApproveDialog() {
      if (this.userRole === 'student') return
      this.approveForm.id = this.selectedLeave.id
      this.approveForm.studentName = this.selectedLeave.studentName
      this.approveForm.teacherName = this.selectedLeave.teacherName
      this.approveDialogVisible = true
    },
    submitApproval() {
      this.$message.success(`审批已提交，结果：${this.approveForm.result === 'approved' ? '批准' : '拒绝'}`)
      this.approveDialogVisible = false
    }
  }
}
</script>

<style scoped>
.leave-apply-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.upload-demo {
  width: 100%;
}

.pagination {
  margin-top: 20px;
  text-align: center;
}
</style>